from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import Book


class BookSerializer(serializers.Serializer):
    name = serializers.CharField(min_length=5, max_length=32, error_messages={
        'min_length': '最少不得少于5个字符',
        'max_length': '最多不得多于32个字符'
    })
    price = serializers.IntegerField(min_value=10, max_value=999, error_messages={
        'min_value': '最少不得少于10元',
        'max_value': '最多不得多于999元'
    })
    publish = serializers.CharField(min_length=3, max_length=255, error_messages={
        'min_length': '最少不得少于3个字符',
        'max_length': '最多不得多于255个字符'
    })

    def validate_task_name(self, name: str):
        if 'sb' in name:
            raise ValidationError('不得包含侮辱性词汇')
        return name

    def validate(self, attrs):
        if attrs.get('name') == attrs.get('publish'):
            raise ValidationError('书名不得与出版社名一致')
        return attrs

    def create(self, validated_data):
        book = Book.objects.create(**validated_data)
        return book

    def update(self, instance, validated_data):
        for key in validated_data.keys():
            setattr(instance, key, validated_data.get(key))
            # print(instance.name)
        instance.save()
        return instance
